<template>
  <div v-loading="loading" class="flex flex-col items-center mt-[10px] ">
    <el-table :width="width" :data="data" :size="size" ref="table" :height="responsiveHeight" @sort-change="sortCahange"
      @selection-change="handleSelectionChange" :border="border" highlight-current-row :row-key="row => row._id"
      @cell-click="handleCellClick" :header-cell-style="headerCellStyle">
      <el-table-column v-if="selection && multiple" type="selection" width="55" :selectable="selectable"
        :reserve-selection="true" />

      <el-table-column v-if="rowNo" type="index" />
      <el-table-column label="选择" width="55" v-if="!multiple" align="center">
        <template #default="{ row }">
          <el-radio-group v-model="radioValue">
            <el-radio :value="row._id" />
          </el-radio-group>
        </template>
      </el-table-column>

      <qa-table-column v-for="item, index in columns" :key="item.key" :prop="item.key" :label="item.title"
        :type="item.type" :column="item" :formatter="item.formatter" :width="item.width" :align="item.align"
        :imageWidth="item.imageWidth" :sortable="item.sortable" :minWidth="item.minWidth" />
      <el-table-column align="center" v-if="rightBtns" width="400" fixed="right">
        <template #header>
          操作
        </template>
        <template #default="scope">
          <el-button :icon="Document" v-if="rightBtns.includes('detail_auto')"
            @click="handleDetail(scope.$index, scope.row)">
            详情
          </el-button>
          <el-button type="primary" :icon="Edit" v-if="rightBtns.includes('update')"
            @click="handleUpdate(scope.$index, scope.row)">
            编辑
          </el-button>

          <el-popconfirm title="确定删除吗？" v-if="rightBtns.includes('delete')"
            @confirm="emit('delete', scope.row, deleteFn)">
            <template #reference>
              <el-button type="danger" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>

          <el-dropdown trigger="click" v-if="rightBtns.includes('more')" class="ml-[12px]">
            <el-button type="success" :icon="ArrowDown">
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="item in rightBtnsMore" :key="item.title" @click="item.onClick(scope.row)"
                  :disabled="transformDisabled(item.disabled, scope.row)">{{ item.title }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block mt-[20px] flex items-center justify-end gap-[20px]" v-if="pagination">
      <span class="text-sm">共 {{ total }} 条</span>
      <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize"
        :page-sizes="[1, 5, 10, 20, 50, 100, 500]" :size="size" background layout="sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        @change="pageIndexChange" />
    </div>
  </div>
  <qa-dialog v-model="detailShow"  title="详情">
    <el-table :data="detailData" border :show-header="false" max-height="800">
      <el-table-column width="200"  prop="title"  />
      <el-table-column  >
        <template #default="scope">
         <qa-table-detail :type="scope.row.type" :formatter="scope.row.formatter" :column="columns[scope.$index]" :row="scope.row" :value="scope.row.value" :index="scope.$index" />
        </template>
      </el-table-column>
    </el-table>
  </qa-dialog>
</template>

<script setup lang="ts">
import { Delete, Edit, ArrowDown, Document } from '@element-plus/icons-vue'
import { ElTable, ElTableColumn } from 'element-plus';
import type { ComponentSize } from 'element-plus';
import type { CSSProperties } from 'vue';
import Http from '@/util/request'
import qaTableColumn from './qa-table-column';
import qaTableDetail from './qa-table-detail';

const table = ref<InstanceType<typeof ElTable>>()

const emit = defineEmits(['update', 'delete', 'select-selection-change', 'select-cell-radio-click', 'current-change']);

interface Columns {
  key: string;
  title: string;
  type: string;
  width?: number; // 可选字段
  minWidth?: number;
  align?: string;
  sortable?: boolean | string;
  mode?: string;
  imageWidth?: number;
  formatter?: (val: any, row: any, column: any, index: any) => any;
  columns?: Columns[];
}

interface QueryFormParam {
  formData: Record<string, any>;
  columns: Columns[];
}

interface BtnsItem {
  title: string;
  disabled?: boolean | ((item: any) => boolean);
  onClick: (row: any) => void;
}

const props = withDefaults(
  defineProps<{
    width?: number;
    height?: number;
    action?: string;
    columns: Columns[];
    queryFormParam?: QueryFormParam;
    rightBtns?: ('detail_auto' | 'update' | 'delete' | 'more')[];  // 定义为数组类型
    rightBtnsMore?: BtnsItem[];
    selection?: boolean;
    rowNo?: boolean;
    border?: boolean;
    pagination?: boolean;
    size?: ComponentSize;
    multiple?: boolean;
    update?: (item: any) => void;
    headerCellStyle?: CSSProperties;
    defaultSelectValue?: any;
    nameKey?: string;
    idKey?: string;
    type?: undefined | 'form' | 'table-select';
    selectionData?: any;
  }>(),
  {
    multiple: true,
    selection: false,
    rowNo: false,
    pagination: true,
    size: 'default',
    idKey: '_id',
    nameKey: '_id',
  }
)

const responsiveHeight = ref(0)

onMounted(() => {
  onResize()
  window.addEventListener('resize', onResize);

})

onUnmounted(() => {
  window.removeEventListener('resize', onResize)
})

const onResize = () => {
  console.log("大小改变")
  if (props.height) {
    responsiveHeight.value = props.height
    return
  };
  const fromHeight = document.querySelector('.el-form')?.clientHeight || 0;
  const rowHeight = document.querySelector('.el-row')?.clientHeight || 0;
  const paginHeight = (document.querySelector(".demo-pagination-block") as HTMLElement)?.offsetHeight || 0;
  responsiveHeight.value = window.innerHeight - fromHeight! - rowHeight! - paginHeight! - 210
}


const selectable = (row: any) => {
  return row.role !== 'admin'
}

const loading = ref(true)
const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)

const sortRule: any = ref([])
const sortCahange = (val: any) => {
  sortRule.value = [
    {
      name: val.prop,
      type: val.order === 'ascending' ? 'asc' : 'desc'
    }
  ]
  getData()
}

const radioValue = ref("")
radioValue.value = props.defaultSelectValue

const handleCellClick = (val: any) => {
  emit('current-change', val)

  if (props.type === 'table-select') {
    if (!props.multiple) {
      if (radioValue.value && props.defaultSelectValue && radioValue.value === val[props.idKey]) {
        radioValue.value = ""
        emit('select-cell-radio-click', undefined)
      } else {
        radioValue.value = val[props.idKey]
        const result = data.value.find((item: any) => item[props.idKey] === val[props.idKey])
        emit('select-cell-radio-click', result)
      }
    }

    if (props.multiple) {
      if (props.selectionData.find((item: any) => item[props.idKey] === val[props.idKey])) {
        table.value && table.value.toggleRowSelection(val, false);
      } else {
        table.value && table.value.toggleRowSelection(val, true);
      }
    }
  }

}


const handleSelectionChange = (val: any) => {
  emit('select-selection-change', val)
}

// 更新某行选中状态
const toggleRowSelection = (val: any) => {
  if (table.value) {
    table.value.toggleRowSelection(val, false);
  }
}

// 设置默认选中状态
const restoreSelectedRows = () => {
  if (props.multiple && props.defaultSelectValue) {
    data.value.forEach((item: any) => {
      if (props.defaultSelectValue.includes(item[props.idKey]) && table.value) {
        table.value.toggleRowSelection(item, true);
      }
    })
  }

  if (!props.multiple) {
    const defaultRadio = data.value.find((item: any) => item[props.idKey] === props.defaultSelectValue)

    if (defaultRadio) {
      radioValue.value = defaultRadio[props.idKey]
    } else {
      radioValue.value = ""
    }
  }
}

const initTableSelection = () => {
  table.value && table.value.clearSelection()
}
const handleCurrentChange = (val: number) => {
  console.log(val)
}

const deleteFn = async ({ action, data }: { action: string, data: any }): Promise<void> => {
  loading.value = true
  try {
    const res = await Http.request({
      url: action,
      method: 'post',
      data
    })
    ElNotification({
      message: '删除成功',
      type: 'success',
    })
    getData()
  } catch (err) {
    loading.value = false
  }

}

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)

}
const pageIndexChange = (currentPage: number, pageSize: number) => {
  console.log(currentPage)
}

const detailShow = ref(false)
const detailData = ref<any>({})
const handleDetail = (index: any, row: any) => {
  console.log("查找",props.columns)
  console.log(index, row)

  // console.log(props.columns.find((item: any) => console.log(item.key === '_add_time')))
  const tableDatas = props.columns.map((item) => {
    console.log(item)
      return {
        value: row[item.key],
        row,
        ...item
      }
  })
  detailData.value = tableDatas
  detailShow.value = true
}

const handleUpdate = (index: any, row: any) => {
  emit('update', { ...row })
}

const handleDelete = (index: any, row: any) => {
  console.log(index, row)
  emit('delete', row)

}
const data = ref<any[]>([])
const getData = async () => {
  loading.value = true
  try {
    const res = await Http.request({
      url: props.action,
      method: 'post',
      data: {
        ...props.queryFormParam,
        "pageIndex": pageIndex.value,
        "pageSize": pageSize.value,
        sortRule: sortRule.value
      }
    })

    data.value = []
    data.value.push(...res.data.data.rows)
    total.value = res.data.data.total
    restoreSelectedRows();
    loading.value = false
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
  }

}
getData()
watch(() => pageSize.value, (newVal, oldVal) => {
  getData()
})

watch(() => pageIndex.value, (newVal, oldVal) => {
  getData()
})

const Search = () => {
  console.log("进行搜索")
  getData()
}

const transformDisabled = (disabled: any, row: any): boolean => {
  if (typeof disabled === 'boolean') return disabled

  if (typeof disabled === 'function') {
    return disabled(row)
  }
  return true
}
defineExpose({
  Search,
  refresh: getData,
  toggleRowSelection,
  initTableSelection
});
</script>

<style scoped></style>
